package com.aiyige.page.publish.selectcourse;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.eventbus.EventSelectCourse;
import com.aiyige.model.Page;
import com.aiyige.model.moment.backup.CourseBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.publish.coursesingleprice.InputSinglePricePage;
import com.aiyige.page.publish.selectcourse.adapter.CourseAdapter;
import com.aiyige.page.publish.selectcourse.model.Course;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

@Route(path = ARouterConfig.SelectCoursePage)
public class SelectCoursePage extends AppCompatActivity implements CommonDataView.RetrofitStub {
    public static final String EXTRA_KEY_SELECT_COURSE_DATA = "com.aiyige.extra.EXTRA_KEY_SELECT_COURSE_DATA";
    public static final int REQUEST_CODE_INPUT_SINGLE_PRICE = 1;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.cdv)
    CommonDataView cdv;

    CourseAdapter courseAdapter;
    @Autowired
    Course[] selectedCourses = null;
    @Autowired
    boolean postEvent = false;
    @Autowired
    int cardType = TraingCardFormModel.CARD_TYPE_UNKNOWN;
    List<Course> cachedCourseStateList;
    int currentPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_course);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        cachedCourseStateList = new LinkedList<>();
        if (selectedCourses != null) {
            for (Course item : selectedCourses) {
                item.setSelected(true);
                cachedCourseStateList.add(item);
            }
        }
        titleTv.setText(R.string.support_course_multi_select);
        titleActionBtn.setText(R.string.ok);

        courseAdapter = new CourseAdapter();
        courseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Course course = courseAdapter.getItem(position);
                if (course.isSelected()) {
                    course.setSelected(false);
                    courseAdapter.setData(position, course);
                    updateCachedCourseState(course);
                } else {
                    if (TextUtils.isEmpty(course.getSinglePrice()) && cardType == TraingCardFormModel.CARD_TYPE_PREPAID_CARD) {
                        currentPosition = position;
                        ARouter.getInstance()
                                .build(ARouterConfig.InputSinglePricePage)
                                .navigation(SelectCoursePage.this, REQUEST_CODE_INPUT_SINGLE_PRICE);
                    } else {
                        course.setSelected(true);
                        courseAdapter.setData(position, course);
                        updateCachedCourseState(course);
                    }
                }

            }
        });
        cdv.config(courseAdapter, this);
        cdv.doRefreshRequest();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_INPUT_SINGLE_PRICE:
                if (resultCode == RESULT_OK) {
                    Course course = courseAdapter.getItem(currentPosition);
                    course.setSinglePrice(data.getStringExtra(InputSinglePricePage.EXTRA_KEY_PRICE));
                    course.setSelected(true);
                    courseAdapter.setData(currentPosition, course);
                    updateCachedCourseState(course);
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public ArrayList<Course> getSelectedItem() {
        ArrayList<Course> coursesList = new ArrayList<>();
        for (Course course : courseAdapter.getData()) {
            if (course.isSelected()) {
                coursesList.add(course);
            }
        }
        return coursesList;
    }

    @Override
    public void onBackPressed() {
        if (postEvent) {
            EventBus.getDefault().post(EventSelectCourse.newBuilder()
                    .resultCode(EventSelectCourse.RESULT_CANCEL)
                    .build());
        }
        super.onBackPressed();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn: {
                finish();
                if (postEvent) {
                    EventBus.getDefault().post(EventSelectCourse.newBuilder()
                            .resultCode(EventSelectCourse.RESULT_CANCEL)
                            .build());
                }
                break;
            }
            case R.id.titleActionBtn: {
                ArrayList<Course> courseList = getSelectedItem();
                if (!courseList.isEmpty()) {
                    Intent data = new Intent();
                    data.putParcelableArrayListExtra(EXTRA_KEY_SELECT_COURSE_DATA, courseList);
                    setResult(RESULT_OK, data);
                    finish();
                    if (postEvent) {
                        EventBus.getDefault().post(EventSelectCourse.newBuilder()
                                .resultCode(EventSelectCourse.RESULT_OK)
                                .courseList(courseList)
                                .build());
                    }
                }
                break;
            }
        }
    }

    public void updateCachedCourseState(Course courseState) {
        boolean find = false;
        for (Course cachedCourseState : cachedCourseStateList) {
            if (cachedCourseState.getId().equals(courseState)) {
                find = true;
                cachedCourseState.setSelected(courseState.isSelected());
                cachedCourseState.setSinglePrice(courseState.getSinglePrice());
                break;
            }
        }
        if (!find) {
            cachedCourseStateList.add(courseState);
        }
    }

    public void restoreCachedCourseState(List<Course> courseList) {
        if (!ListUtil.isEmpty(cachedCourseStateList)) {
            outerLoop:
            for (Course cachedCourseState : cachedCourseStateList) {
                for (Course course : courseList) {
                    if (cachedCourseState.getId().equals(course.getId())) {
                        course.setSelected(cachedCourseState.isSelected());
                        if (TextUtils.isEmpty(course.getSinglePrice())) {
                            course.setSinglePrice(cachedCourseState.getSinglePrice());
                        }
                        continue outerLoop;
                    }
                }
            }
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().availableCourse(currentPage, 15);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<CourseBackup> courseBackupList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                courseBackupList.addAll(JSON.parseArray(page.getContent(), CourseBackup.class));
            }
            List<Course> respCourseList = new LinkedList<>();
            for (CourseBackup courseBackup : courseBackupList) {
                int courseType;
                switch (courseBackup.getSubject()) {
                    case Moment.SUBJECT_MAJOR_COURSE:
                        courseType = Course.TYPE_MAJOR_COURSE;
                        break;
                    case Moment.SUBJECT_TRAINING_COURSE:
                        courseType = Course.TYPE_TRAING_CLASS;
                        break;
                    default:
                        courseType = Course.TYPE_MAJOR_COURSE;
                        break;
                }
                respCourseList.add(Course.newBuilder()
                        .id(courseBackup.getId())
                        .singlePrice(courseBackup.getUnitPrice() == null ? null : StringUtils.priceFormat(courseBackup.getUnitPrice()))
                        .selected(false)
                        .title(courseBackup.getTitle())
                        .type(courseType)
                        .courseNum(courseBackup.getClassCount() == null ? null : String.valueOf(courseBackup.getClassCount()))
                        .totalPrice(courseBackup.getPrice() == null ? null : StringUtils.priceFormat(courseBackup.getPrice()))
                        .singlePriceEditable(courseBackup.getUnitPrice() == null)
                        .build());
            }
            restoreCachedCourseState(respCourseList);
            resultList.addAll(respCourseList);
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }
}
